﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using static CoreWebApiNuGet.ApiContracts.ApiResults;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using CoreWebApiNuGet.ApiContracts;

namespace CoreWebApiNuGet.ActionFilter
{
    /// <summary>
    /// 数据请求动作过滤器
    /// </summary>
    public class ApiResponseActionFilter : IActionFilter
    {
        /// <summary>
        /// 调用前执行
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var keys = context.ModelState.Keys;

                List<ValidationError> ErrorList = new List<ValidationError>();

                foreach (var item in keys)
                {
                    ValidationError ErrorMessage = context.ModelState.Keys.SelectMany(key => context.ModelState[item].Errors.Select(x => new ValidationError(item, x.ErrorMessage))).FirstOrDefault();

                    // 注释>>暂不处理枚举转换
                    //if (IsNumber(ErrorMessage.Message))
                    //{
                    //    ErrorMessage.Message = int.Parse(ErrorMessage.Message).GetDesString<HttpCodeEnum>();
                    //}

                    ErrorList.Add(ErrorMessage);
                }

                BaseResultMsg resultMsg = ApiResults.ReturnError(string.Empty, ErrorList);
                context.Result = new JsonResult(resultMsg);
            }
        }

        /// <summary>
        /// 调用后执行
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult objectResult)
            {
                var apiResponse = new BaseResultMsg
                {
                    ResultCode = context.HttpContext.Response.StatusCode,
                    ResultMsgs = "", // 根据需要设置消息
                    ResultType = "Success",
                    ResultData = objectResult.Value
                };

                context.Result = new ObjectResult(apiResponse)
                {
                    StatusCode = objectResult.StatusCode
                };
            }
        }

        /// <summary>
        /// 错误参数接收实体
        /// </summary>
        public class ValidationError
        {
            public ValidationError(string field, string message)
            {
                Field = field != string.Empty ? field : null;
                Message = message;
            }

            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string Field { get; set; }

            public string Message { get; set; }
        }

        /// <summary>
        /// 检查字符串是否全为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumber(string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return false;
            const string pattern = "^[0-9]*$";
            Regex rx = new Regex(pattern);
            return rx.IsMatch(str);
        }
    }
}
